﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;
using System.Reflection;
using OfficeOpenXml;
using OfficeOpenXml.Table;

namespace Framework.Excel
{

    /// <summary>
    /// 
    /// </summary>
    public static class ExcelExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static Stream ToExcel(this DataTable dt, string sheetName = "")
        {
            using (ExcelPackage pck = new ExcelPackage())
            {
                var wsDt = pck.Workbook.Worksheets.Add(sheetName.Or(dt.TableName));
                wsDt.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.Medium9);
                wsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();
                pck.Save();
                return pck.Stream;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static Stream ToExcel<T>(this List<T> list, string sheetName = "")
        {
            using (ExcelPackage pck = new ExcelPackage())
            {
                var wsDt = pck.Workbook.Worksheets.Add(sheetName.Or(typeof(T).Name));
                wsDt.Cells["A1"].LoadFromCollection(list, true, TableStyles.Medium9);
                wsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();
                pck.Save();
                return pck.Stream;
            }
        }
    }
}
